package org.xs.web.http.validate;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xs.web.http.i18n.Location;

public class ValidateEntry {
	private String controller;
	private String action;
	private Map<String,ValidateMethod[]> validateMethods = new HashMap<String,ValidateMethod[]>();
	
	
	public ValidateEntry(String controller,String action){
		this.controller = controller;
		this.action = action;
	}
	
	
	public void addField(String field,ValidateMethod[] method){
		validateMethods.put(field, method);
	}
	
	
	
	public String getController() {
		return controller;
	}

	public String getAction() {
		return action;
	}

	public List<FieldErrorMsg> validate(Map<String,Object> form){
		List<FieldErrorMsg> errorMsg = new ArrayList<FieldErrorMsg>();
		
		ValidateMethod[] vms = null; 
		String key = null;
		for(Map.Entry<String,ValidateMethod[]> field : validateMethods.entrySet()){
			vms = field.getValue();
			if(vms != null){
				key = getKey(field.getKey());
				for(ValidateMethod m: vms){
					if(!m.apply(form.get(field.getKey()))){
						errorMsg.add(new FieldErrorMsg(field.getKey(),name(key,field.getKey()),msg(key,m.getMsg())));
						break;
					}
				}
			}
		}
		return errorMsg;
	}
	public String name(String key,String fieldName){
		Location loc = Location.create();
		String res = loc.message(key+"_name");
		return res == null ? fieldName : res;
	}
	
	public String msg(String key,String msgKey){
		String msg = null;
		Location loc = Location.create();
		if(msgKey == null || msgKey.length() < 1){
			msg = loc.message(key);
			msg = msg == null ? key : msg;
		}else if(msgKey.charAt(0) == '$'){
			msg = loc.message(msgKey.substring(1));
			msg = msg == null ? msgKey : msg;
		}else{
			msg = msgKey;
		}
		return msg == null ? "" : msg;
	}
	
	public String getKey(String field){
		String key=null;
		if(controller ==null || controller.length() < 1){
			key = action+"_"+field;
		}else{
			key = controller+"_"+action+"_"+field;
		}
		return key;
	}
	
	
}
